package com.learn.ch02ttlqueue.confim_advance.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/08/24
 * @description ch08 发布确认
 * 自定义回调处理器
 */
@Component
@Slf4j
public class MyCallBack implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @PostConstruct // 要确保rabbitTemplate有这个回调
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
//        rabbitTemplate.setMandatory(true);
    }

    /**
     * 未到达交换机时触发
     * @param correlationData correlation data for the callback.
     * @param ack true for ack, false for nack
     * @param cause An optional cause, for nack, when available, otherwise null.
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData!=null ? correlationData.getId() : "";
        if (ack) {
            log.info("消息成功到达交换机, id: {}", id);
        } else {
            log.warn("消息未到达交换机，具体细节：\n{}", correlationData);
        }
    }

    /**
     * 默认不可路由的消息会直接丢弃
     * 到达交换机却不可路由时触发
     * @param returned the returned message and metadata.
     */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.warn("消息未到达消费者，具体细节：\n{}", returned);

    }
}
